package myserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import java.io.*;


public class MyServer {

	public static void main(String args[]) {

		try {
			ServerSocket server = new ServerSocket(8079);
			System.out.print("I am up!");
			while (true) {

				Socket client = server.accept();

				byte[] binaryData = new byte[43200];

				client.getInputStream().read(binaryData);

				createJpgFile(binaryData);

				client.close();
			}

		} catch (IOException e) {

			System.out.println(e);
		}

	}

	static public String createJpgFileFolder() {

		try {
			String folderPath = "C:\\TestPicure";
			String folderName = folderPath + "2";

			File folder = new File(folderName);

			if (!folder.exists()) {
				folder.mkdirs();
			}
			return folderName + "\\";

		} catch (Exception e) {

			System.out.println(e);
			return null;
		}
	}

	static public String createCurrentFileName() {
		Calendar cal = Calendar.getInstance();

		return String.valueOf(cal.getTimeInMillis()) + ".jpg";
	}

	static public void createJpgFile(byte[] dataContent) {

		try {
			String filePath = createJpgFileFolder();

			String fileName = null;

			if (filePath != null) {
				fileName = filePath + createCurrentFileName();
			}

			File myFile = new File(fileName);
			myFile.createNewFile();

			FileOutputStream fos = new FileOutputStream(myFile);
			fos.write(dataContent);

			fos.flush();
			fos.close();
			// fileIn.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}
}
